package com.coocaa.x.demo.servlets.utils;

import android.content.Context;

import com.coocaa.x.framework.app.CoocaaApplication;
import com.coocaa.x.framework.utils.LogUtils;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by admin on 2015/9/12.
 */
public class FileDownload {
    public static final String tag = "down";


    public static void downLoadApp(final DownloadListener listener,final String downURL) {
        final String savePath = getDataDir()+guessName(downURL);
        LogUtils.d(tag, "downLoadPicture--downURL--savePath-"
                + downURL + "  " + savePath);
//        if (new File(savePath).exists()) {
//            LogUtils.d(tag, "download  already!!!!!!!!!!path=" + savePath);
//            return;
//        }
        new Thread() {

            private Timer mTimer = null;
            private TimerTask mTimerTask = null;
            private long cur_length = 0;
            private long total_length = 0;

            private void startTimer()
            {
                if (mTimerTask != null) {
                    mTimerTask.cancel();
                }
                if (mTimer != null) {
                    mTimer.cancel();
                }

                mTimer = new Timer();
                mTimerTask = new TimerTask() {
                    @Override
                    public void run() {
//                        LogUtils.d(tag, "run current length :" + cur_length);
                        LogUtils.d(tag, "run current thread"+Thread.currentThread().getId()+" cur_leangth:"+cur_length+" % :" + (int)(cur_length * 100 / total_length) );
                        listener.onDownloading(downURL,(int)(cur_length * 100 / total_length));
                    }
                };
                listener.startDownload(downURL);
                mTimer.schedule(mTimerTask,0,1000);
            }

            private void cancleTimer()
            {
                LogUtils.d(tag, "cancleTimer");
                listener.finishDownload(downURL,savePath);
                if (mTimerTask != null)
                    mTimerTask.cancel();
                if (mTimer != null) {
                    mTimer.cancel();
                    mTimer = null;
                }
            }

            @Override
            public void run() {
                // TODO Auto-generated method stub
                try {
                    // 构造URL
                    URL url = new URL(downURL);
                    // 打开连接
                    URLConnection con = url.openConnection();
                    // 获得文件的长度
                    total_length = con.getContentLength();
                     LogUtils.d(tag,"长度 :"+total_length);
                    // 输入流
                    InputStream is = con.getInputStream();
                    // 1K的数据缓冲
                    byte[] bs = new byte[1024];
                    int len = 0;
                    // 输出的文件流
                    OutputStream os = new FileOutputStream(savePath);
                    startTimer();
                    // 开始读取
                    while ((len = is.read(bs)) != -1) {
                        os.write(bs, 0, len);
                        cur_length += len;
//                        LogUtils.d(tag, "current length :" + len);
                    }
                    // 完毕，关闭所有链接
                    os.flush();
                    os.close();
                    is.close();
                    cancleTimer();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }.start();
    }

    public static String getDataDir()
    {
        return CoocaaApplication.getContext().getDir("downloadTest",
                Context.MODE_WORLD_WRITEABLE | Context.MODE_WORLD_READABLE).getAbsolutePath()
                + "/";
    }

    private static String guessName (String url)
    {
        String name = url.substring(url.lastIndexOf("/")+1);
        return name;
    }
}
